package site.wenneng.dev.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.wenneng.dev.objs.po.HolidayPO;
import site.wenneng.dev.dao.HolidayMapper;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HolidayService {

    @Autowired
    private HolidayMapper mapper;

    private Map<Long, HolidayPO> holidayMap;

    public synchronized Map<Long, HolidayPO> getHolidayMap() {
        if (holidayMap == null) {
            holidayMap = mapper.selectList(Wrappers.query()).stream()
                    .collect(Collectors.toMap(HolidayPO::getDate, item -> item, (o1, o2) -> o1));
        }
        return holidayMap;
    }

    public LocalDate getNextWorkday(LocalDate date) {
        LocalDate next = date;
        while (true) {
            next = next.plusDays(1);
            HolidayPO holiday = getHoliday(next);
            if (holiday == null || holiday.getWorkday() == 1) {
                return next;
            }
        }
    }

    public List<HolidayPO> listCurrentWeekDay(LocalDate date) {
        LocalDate firstDayOfWeek = date.minusDays(date.getDayOfWeek().getValue() - 1);
        List<HolidayPO> holidayList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            holidayList.add(getHoliday(firstDayOfWeek.plusDays(i)));
        }
        return holidayList;
    }

    public HolidayPO getHoliday(LocalDate date) {
        Map<Long, HolidayPO> map = getHolidayMap();
        return map.get(getLongDate(date));
    }

    @NotNull
    private Long getLongDate(LocalDate date) {
        return Long.parseLong(date.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
    }

}
